package badgegenerator.dao;

import badgegenerator.dao.mybatis.MyBatisConnector;
import badgegenerator.dao.mybatis.IEmployeeMapper;
import badgegenerator.dao.exceptions.DAOException;
import badgegenerator.dao.exceptions.MyBatisInitException;
import badgegenerator.model.Employee;
import java.util.List;
import org.apache.ibatis.session.SqlSession;

public class EmployeeDAO {
    public Employee getEmployeeById(Integer id) throws DAOException{
        Employee resultEmployee = null;
        SqlSession session = null;
        try{
            session = MyBatisConnector.getSession(false);
            IEmployeeMapper mapper = session.getMapper(IEmployeeMapper.class);
            resultEmployee = mapper.getEmployeeById(id);
        }
        catch(MyBatisInitException ex){
            throw new DAOException(ex);
        }
        finally{
            if(session != null)
                session.close();
        }
        
        return resultEmployee; 
    }
    
    public List<Employee> getAllEmployees() throws DAOException{
        List<Employee> resultEmployeeList = null;
        SqlSession session = null;
        try{
            session = MyBatisConnector.getSession(false);
            IEmployeeMapper mapper = session.getMapper(IEmployeeMapper.class);
            resultEmployeeList = mapper.getAllEmployees();
        }
        catch (MyBatisInitException ex) {        
            throw new DAOException(ex);
        }        
        finally{
            if(session != null)
                session.close();
        }
        
        return resultEmployeeList;
    }
    
    public void saveOrUpdate(Employee employee) throws DAOException{
        SqlSession session = null;
        try{
            session = MyBatisConnector.getSession(false);
            IEmployeeMapper mapper = session.getMapper(IEmployeeMapper.class);
            if(employee.getId() == null){
                mapper.insert(employee);
            }
            else{
                mapper.update(employee);
            }
            session.commit();
        }
        catch (MyBatisInitException ex) {        
            throw new DAOException(ex);
        }        
        finally{
            if(session != null)
                session.close();
        }
    }
    
    public void delete(Employee employee) throws DAOException{
        if(employee.getId() == null)
            throw new DAOException("Employee should have setted id");
        SqlSession session = null;
        try{
            session = MyBatisConnector.getSession(false);
            IEmployeeMapper mapper = session.getMapper(IEmployeeMapper.class);
            mapper.delete(employee);
            session.commit();
        }
        catch (MyBatisInitException ex) {        
            throw new DAOException(ex);
        }        
        finally{
            if(session != null)
                session.close();
        }
    }
}
